<template>
  <div class="orders-page">
    <Header />

    <div class="page-content">
      <!-- 面包屑导航 -->
      <div class="page-nav">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/account' }">
              <i class="fas fa-chevron-left"></i> {{ $t('返回账户') }}
            </el-breadcrumb-item>
            <el-breadcrumb-item>{{ $t('我的订单') }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>

      <!-- 主要内容 -->
      <div class="main-card">
        <h1 class="page-title">{{ $t('我的订单') }}</h1>

        <!-- 订单筛选 -->
        <div class="filter-bar">
          <el-tabs v-model="orderStatus" @tab-change="handleStatusChange">
            <el-tab-pane :label="$t('全部订单')" name="" />
            <el-tab-pane :label="$t('待支付')" name="0" />
            <el-tab-pane :label="$t('已支付')" name="1" />
            <el-tab-pane :label="$t('已关闭')" name="2" />
            <el-tab-pane :label="$t('待收货')" name="3" />
            <el-tab-pane :label="$t('已完成')" name="4" />
            <el-tab-pane :label="$t('退款详情')" name="5,6,7" />
            <!-- <el-tab-pane :label="$t('退款待审核')" name="5" />
            <el-tab-pane :label="$t('已退款')" name="6" />
            <el-tab-pane :label="$t('退款详情')" name="7" /> -->
            <el-tab-pane :label="$t('回收')" name="8,9,10" />
            <!-- <el-tab-pane :label="$t('回收成功')" name="9" />
            <el-tab-pane :label="$t('回收失败')" name="10" /> -->
          </el-tabs>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              :placeholder="$t('搜索订单号/商品名称')"
              clearable
              @change="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search"></i>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 订单列表 -->
        <div class="order-list">
          <el-empty v-if="orders.length === 0" :description="$t('暂无数据')" />
          <div
            v-for="order in orders"
            :key="order.id"
            class="order-item"
          >
            <div class="order-header">
              <div class="order-info">
                <span class="order-id">{{ $t('订单号') }}：{{ order.orderNo }}</span>
                <span class="order-time">{{ order.createTime }}</span>
              </div>
              <div class="order-status" :class="order.status">
                {{ getStatusText(order.status) }}
                <el-text v-if="order.status === 0" size="small" type="danger">({{ $t('失效时间：') }} {{ order.addTimeCountDown }} )</el-text>
                <el-text v-if="order.status === 3" size="small" type="danger">({{ $t('确认收货剩余时间：') }} {{ order.deliverTimeCountDown }} )</el-text>
              </div>
            </div>

            <div class="order-content">
              <div class="product-list">
                <div
                  v-for="product in toStringAdd(order.productInfo)"
                  :key="product.productId"
                  class="product-item"
                  @click="goToDetail(product,order)"
                >
                  <img :src="product.productImage" :alt="product.name" class="product-image">
                  <div class="product-info">
                    <h3 class="product-name">{{ product.productName }}</h3>
                    <p class="product-price">
                      <span class="price">{{ langStore.languageSymbol }}{{ product.submitPrice*langStore.languageRate }}</span>
                      <span class="quantity">x {{ product.productNum }}</span>
                    </p>
                  </div>
                </div>
              </div>

              <div class="order-summary">
                <div class="total-info">
                  <p>{{ $t('共') }} {{ totalQuantitySun(toStringAdd(order.productInfo)) }} {{ $t('件商品') }}</p>
                  <p>{{ $t('会员折扣') }}：{{order.discountRate*100}}%</p>
                  <!-- <p>{{ $t('折扣后金额') }}：{{order.discountMoney}}</p> -->
                  <!-- userVipLevelRate -->
                  <p class="total-price">
                    {{ $t('实付款') }}：<span>{{ langStore.languageSymbol }}{{ order.discountMoney*langStore.languageRate }}</span>
                    <span class="original-price">{{ langStore.languageSymbol }}{{ order.price  }}</span>
                    <!-- <span class="original-price">{{ langStore.languageSymbol }}{{ totalQuantitySunasd(toStringAdd(order.productInfo)) }}</span> -->
                  </p>
                  <p class="total-price" v-if="order.type == '1'&& [1,3].includes(order.status)">
                    {{ $t('回收价格') }}：<span>{{ langStore.languageSymbol }}{{ order.recyclePrice*langStore.languageRate }}</span>
                  </p>
                </div>
                <div class="order-actions">
                  <el-button
                    v-if="order.status == '0'"
                    type="primary"
                    :disabled="order.addTimeCountDown === '00:00:00'"
                    @click="handlePay(order)"
                  >
                    {{ $t('立即付款') }}
                  </el-button>
                </div>
                <div class="order-actions">
                  <el-button
                    v-if="order.type == '1'&& [1,3].includes(order.status)"
                    type="primary"
                    @click="RecyclePay(order)"
                  >
                    {{ $t('回收') }}
                  </el-button>
                </div>
                <div class="order-actions">

                  <el-tag type="warning" v-if="order.type == '1' && order.status == 8">{{ $t('回收待审核') }}</el-tag>
                  <el-tag type="warning" v-if="order.type != '1' && order.status == 8">{{ $t('待审核') }}</el-tag>
                  <el-tag type="success" v-if="order.status == 9">{{ $t('成功') }}</el-tag>
                  <el-tag type="danger" v-if="order.status == 10">{{ $t('失败') }}</el-tag>
                </div>
                <div class="order-actions">
                  <el-button
                    v-if="[3].includes(order.status) && order.type != '1'"
                    type="primary"
                    @click="ReturnOrder(order)"
                  >
                    {{ $t('退款') }}
                  </el-button>
                </div>
                <div class="order-actions">
                  <el-tag type="warning" v-if="order.status == 5">{{ $t('退款待审核') }}</el-tag>
                  <el-tag type="success" v-if="order.status == 6">{{ $t('已退款') }}</el-tag>
                  <el-tag type="danger" v-if="order.status == 7">{{ $t('退款驳回') }}</el-tag>
                </div>
                <!--  -->
              </div>

            </div>
          </div>
        </div>

        <!-- 分页器 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import type { TabPaneName } from 'element-plus'
import Footer from '@/components/Footer.vue'
import { ApiOrderList } from '@/api/order'
import {ApiAddCart, ApiConfirmPay, neworderReturnOrder, neworderRecycle, ApiBuyNow} from "@/api/commodity.js";
import {ElLoading, ElMessage,ElMessageBox } from "element-plus";
import useUserStore from '@/store/modules/user'
import useLangStore from '@/store/modules/lang'
import {useI18n} from "vue-i18n";
import { ApiConfig } from '@/api/common'
import { countDown } from '@/utils/utils'

const { t } = useI18n();
const langStore = useLangStore()
const userStore = useUserStore();
const router = useRouter();
//折扣率
const userVipLevelRate = ref(userStore.userInfo?.member?.userVipLevelRate || 0)

// 获取订单配置
const orderConfig = ref({})
const getOrderConfig = async () => {
  try {
    const response = await ApiConfig({
      key: 'ORDER_SETTING'
    })
    orderConfig.value = response.data
  } catch (error) {}
}

//跳转
const goToDetail = (propsproduct,otred) => {
  console.log(propsproduct,'propsproduct');
  if(otred.type == 1){
    router.push(`/deals/${propsproduct.productId}`)
  }else{
    router.push('/products/detail/' + propsproduct.productId)
  }
}
// 订单状态
const orderStatus = ref('')
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const productNum = ref(1);



// 模拟订单数据
const orders = ref([])
const toStringAdd = (jsonString)=>{

  const jsonObject = JSON.parse(jsonString); // 将 JSON 字符串解析为对象
  // console.log(jsonObject,'jsonObject');

  return jsonObject
}
//
// 计算商品总数量
const totalQuantitySun = (totalproducts)=> {
  // console.log(totalproducts,'totalproducts');
  // order.totalQuantity
  let sun
  sun = totalproducts.reduce((sum, product) => sum + product.productNum, 0);
  // console.log(totalproducts,'totalproducts');

  return sun
      // return totalproducts.reduce((sum, product) => sum + product.productNum, 0);
}
// 计算商品总价格
const totalQuantitySunasd = (totalproducts)=> {

  // console.log(totalproducts,'totalproducts');
  // // order.totalQuantity
  let sun
  sun = totalproducts.reduce((sum, product) => sum + product.submitPrice * langStore.languageRate * product.productNum, 0);
  // console.log(totalproducts,'totalproducts');
  if(userVipLevelRate.value == 0){
    return sun
  }else{
    return sun*userVipLevelRate.value
  }
}
let timer;
const getOrderList = async () => {
  console.log(orderStatus.value,'orderStatus.value', orderConfig.value);
  let arrOn: string[] = []; // 显式声明为字符串数组
  arrOn.push(orderStatus.value)
  const params = {
    status:orderStatus.value == ''?'':arrOn,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    keyword: searchKeyword.value
  }
  const loading = ElLoading.service()
  try {
    const res = await ApiOrderList(params)
    orders.value = res.rows.map(e => {
      return{
        ...e,
        addTime: e.addTime ? new Date(e.addTime).getTime() + (orderConfig.value.autoCancel || 0) * 60 * 1000 : '', // 待支付倒计时
        deliverTime: e.deliverTime ? new Date(e.deliverTime).getTime() + (orderConfig.value.autoReceive || 0) * 24 * 60 * 60 * 1000 : '', // 待收货倒计时
      }
    })
    console.log(orders.value.deliverTime,'orders.value');

    total.value = res.total
    // 启动定时器
    timer = setInterval(updateCountdown, 1000); // 每秒更新一次
    loading.close()
  } catch (error) {
    loading.close()
  }
}

// 更新倒计时
const updateCountdown = () => {
  orders.value.forEach((item) => {
    const addTimeTime = item.addTime - new Date().getTime();
    if (addTimeTime > 0) {
      item.addTimeCountDown = formatTimeText(addTimeTime);
    } else {
      item.addTimeCountDown = '00:00:00'; // 倒计时结束
    }
    const deliverTime = item.deliverTime - new Date().getTime();
    if (deliverTime > 0) {
      item.deliverTimeCountDown = formatTimeText(deliverTime);
    } else {
      item.deliverTimeCountDown = '00:00:00'; // 倒计时结束
    }
  })
};
// 格式化时间为时分秒
const formatTimeText = (time) => {
  const hours = Math.floor(time / (1000 * 60 * 60));
  const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((time % (1000 * 60)) / 1000);
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    0: t('待支付'),
    1: t('已支付'),
    2: t('已关闭'),
    3: t('待收货'),
    4: t('已完成'),
    5: t('退款详情'),
    6: t('退款详情'),
    7: t('退款详情'),
    8: t('退款详情'),
    9: t('退款详情'),
    10: t('回收'),
  }
  return statusMap[status] || status
}

// 处理函数
const handleStatusChange = (name: TabPaneName) => {
  const status = name as string
  // TODO: 根据状态筛选订单
  console.log('订单状态:', status);
  getOrderList();
  currentPage.value = 1;
  pageSize.value = 10;
  searchKeyword.value = '';
}

const handleSearch = (keyword: string) => {
  // TODO: 搜索订单
  console.log('搜索关键词:', keyword)
}
//立即支付

const handlePay = (order: any) => {
  console.log(order,'order');
  ElMessageBox.prompt(t('请输入资金密码'), t('提示'), {
    confirmButtonText: t('确定'),
    cancelButtonText: t('取消'),
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    inputType: 'password',
    inputPattern: /^\d{6}$/,
    inputErrorMessage: t('资金密码为6位数字')
  }).then(({ value }) => {
    // console.log('支付密码是' + value)
    const loading = ElLoading.service()
    ApiConfirmPay({
      orderNos: [order.orderNo],
      assetPwd:value
    }).then(() => {
      ElMessage.success(t('购买成功'));
      getOrderList();
    }).finally(() => {
      loading.close();
      getOrderList();
    })
  }).catch(() => {
    console.log('取消输入')
  });
  // router.push({
  //   path: '/products/checkout',
  //   query: {
  //     productId: order.products[0].id,
  //     quantity: order.totalQuantity,
  //     orderId: order.id,
  //     orderNo: order.orderNo,
  //     fromOrder: 'true'
  //   }
  // })
}
//回收
const RecyclePay = (order: any) => {

  const loading = ElLoading.service()
  neworderRecycle({
    orderNos: [order.orderNo]
  }).then(() => {
    ElMessage.success(t('回收提交成功'));
    getOrderList();
  }).finally(() => {
    loading.close();
    getOrderList();
  })
}
//退款
const ReturnOrder = (order: any) => {
  ElMessageBox.confirm(t('你确定要退款吗?'))
    .then(() => {
        const loading = ElLoading.service()
          neworderReturnOrder({
            orderNos: [order.orderNo]
          }).then(() => {
            ElMessage.success(t('退款提交成功'));
            getOrderList();
          }).finally(() => {
            loading.close();
            getOrderList();
          })
          })
    .catch(() => {
      // catch error
    })

}
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // TODO: 重新加载数据
  getOrderList();
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // TODO: 重新加载数据
  getOrderList();
}

onMounted( async () => {
  await getOrderConfig()
  await getOrderList();
})
// 清除定时器
onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style lang="scss" scoped>
@use './style/orders.scss';
</style>
